import { parseXmlFeed } from './parser.js'
import { renderChannels } from './render-reader.js'
import { fetchAll, setStorage, getStorage } from '../../bridge.js'

export const name = 'RSS阅读器'

const { Modal, Input, Form } = window.antd
const h = window.React.createElement

const defaultConfig = [
  'https://www.ruanyifeng.com/blog/atom.xml',
  'https://mdhweekly.com/rss.xml',
  'https://fed.chanceyu.com/atom.xml',
]

class RssReader extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      config: defaultConfig,
      showDialog: false,
      list: [],
      refreshTime: '',
    }
    this.form = React.createRef()

    this.init()
  }

  init = async () => {
    const config = await getStorage('rssConfig')
    if (config) {
      this.setState({
        config,
      })
    }
    this.loadData(true)
  }

  loadData = async (useCache) => {
    try {
      this.setState({
        loading: true,
      })
      const { data, timestamp } = await fetchAll(
        this.state.config,
        useCache ? 'rss' : null
      )
      if (!data) return
      const list = data.map((p) => ({
        url: p.url,
        ...parseXmlFeed(p.content),
      }))
      this.setState({
        list,
        refreshTime: new Date(timestamp).toLocaleString(),
      })
    } finally {
      this.setState({
        loading: false,
      })
    }
  }

  handleRefresh = () => {
    this.loadData(false)
  }

  openSetting = () => {
    this.setState({
      showDialog: true,
    })
  }

  onFinish = (values) => {
    const { configStr } = values
    const config = configStr
      .split('\n')
      .map((p) => p.trim())
      .filter((p) => p)
    this.setState({
      config,
    })
    setStorage('rssConfig', config)
    this.loadData(false)
  }

  render() {
    const { config, showDialog, list, refreshTime, loading } = this.state
    return h(
      'div',
      { className: 'rss' },
      h(
        'div',
        { className: 'rss-title' },
        h(
          'div',
          { className: 'rss-title-time' },
          h('i', {
            className: `workdial wd-refresh ${loading ? 'loading' : ''}`,
            style: { marginRight: '4px' },
            onClick: this.handleRefresh,
          }),
          '最近刷新时间：',
          h('span', null, refreshTime)
        ),
        h(
          'div',
          null,
          h('i', {
            id: 'setting-btn',
            className: 'workdial wd-setting',
            onClick: () => this.setState({ showDialog: true }),
          })
        )
      ),
      h('div', { className: 'rss-content' }, renderChannels(list)),
      h(
        Modal,
        {
          title: '配置rss源',
          open: showDialog,
          width: 400,
          okText: '保存',
          cancelText: '取消',
          onCancel: () => this.setState({ showDialog: false }),
          onOk: async () => {
            const valid = await this.form.current.validateFields()
            if (valid) {
              this.form.current.submit()
              this.setState({
                showDialog: false,
              })
            }
          },
        },
        h(
          Form,
          {
            ref: this.form,
            name: 'basic',
            initialValues: {
              configStr: config.join('\n'),
            },
            onFinish: this.onFinish,
            autoComplete: 'off',
          },
          h(
            Form.Item,
            {
              name: 'configStr',
              rules: [{ required: true, message: '请输入rss源' }],
            },
            h(Input.TextArea, {
              rows: 6,
              placeholder: '请输入rss源链接，每行一个',
              allowClear: true,
            })
          )
        )
      )
    )
  }
}

let app
export const render = ({ root }) => {
  app = ReactDOM.createRoot(root)
  app.render(h(RssReader, null))
}

export const unmount = () => {
  app && app.unmount()
}
